/**
 * Copyright 2009-2019 the original author or authors.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package drds.common.db.xml_mapping.script.xml_tags;

import drds.common.db.xml_mapping.builder.SqlSourceBuilder;
import drds.common.db.xml_mapping.mapping.BindSql;
import drds.common.db.xml_mapping.mapping.SqlSource;
import drds.common.db.xml_mapping.session.Configuration;

/**
 * @author Clinton Begin
 */
public class DynamicSqlSource implements SqlSource {

  private final Configuration configuration;
  private final DynamicNode rootNode;

  public DynamicSqlSource(Configuration configuration, DynamicNode rootNode) {
    this.configuration = configuration;
    this.rootNode = rootNode;
  }

  @Override
  public BindSql getBoundSql(Object parameterObject) {
    DynamicNodeContext dynamicNodeContext = new DynamicNodeContext(configuration, parameterObject);
    rootNode.apply(dynamicNodeContext);
    SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration);
    Class<?> parameterType = parameterObject == null ? Object.class : parameterObject.getClass();
    SqlSource sqlSource = sqlSourceParser.parse(dynamicNodeContext.getSql(), parameterType, dynamicNodeContext.getBindings());
    BindSql bindSql = sqlSource.getBoundSql(parameterObject);
    dynamicNodeContext.getBindings().forEach(bindSql::setAdditionalParameter);
    return bindSql;
  }

}
